﻿using EasyCode.Entity;
using RazorEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace EasyCode.FunServicer
{
    public class StringServicer
    {

        public static string FirstCharToUpper(string str)
        {
            return Regex.Replace(str, @"^\w", t => t.Value.ToUpper());
        }

        public static string ConvertCamelName(string str)
        {
            str = str.Trim(new char[] {'_'});
            Match mt = Regex.Match(str, @"_(\w*)*");
            while (mt.Success)
            {
                var item = mt.Value;
                while (item.IndexOf('_') >= 0)
                {
                    string newUpper = item.Substring(item.IndexOf('_'), 2);
                    item = item.Replace(newUpper, newUpper.Trim('_').ToUpper());
                    str = str.Replace(newUpper, newUpper.Trim('_').ToUpper());
                }
                mt = mt.NextMatch();
            }
            return str;
        }

        /// <summary>
        /// 根据模板和模型，确定生成代码的文件名称。
        /// </summary>
        /// <param name="templateFile"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string BuildCodeFileName(string templateFile, BuildCodeEntity model)
        {
            FileInfo fileInfo = new FileInfo(templateFile);
            string fileName = fileInfo.Name.Replace("[TableName]", model.TableCapitalizedCamelName)
                .Replace(".template", "").Replace(".TEMPLATE", "");
            return fileName;
        }

        /// <summary>
        /// 根据模板和模型，确定生成代码的内容。
        /// </summary>
        /// <param name="templateFile"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string BuildCodeContent(string templateFile, BuildCodeEntity model)
        {
            string resultContent = string.Empty;
            string templateContent = System.IO.File.ReadAllText(templateFile, System.Text.Encoding.GetEncoding("GBK"));
            if (!string.IsNullOrEmpty(templateContent))
            {
                try
                {
                    resultContent = Razor.Parse<BuildCodeEntity>(templateContent, model);
                }
                catch (Exception ex)
                {
                    resultContent = ex.Message;
                }
            }
            return resultContent;
        }

    }
}
